package com.xiaoaoc.SmartToilet.controller;


import com.xiaoaoc.SmartToilet.dto.ApiResponse;
import com.xiaoaoc.SmartToilet.model.User;
import com.xiaoaoc.SmartToilet.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> register(@RequestBody User user) {
        if(userService.findByUserName(user.getUserName()).isPresent()){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new ApiResponse<>("用户名已存在！"));
        }
        else {
            User savedUser = userService.register(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(new ApiResponse<>(savedUser));
        }

    }

    @GetMapping("/login")
    public ResponseEntity<ApiResponse<User>> login(@RequestParam String username, @RequestParam String password) {
        User savedUser = userService.login(username, password);
        if(savedUser==null){
            return  ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new ApiResponse<>("账户或密码错误"));
        }
        return ResponseEntity.status(HttpStatus.OK).body(new ApiResponse<>(savedUser));
    }

    @PostMapping("/change-avatar-url")
    public ResponseEntity<ApiResponse<User>> changeAvatarUrl(@RequestParam String username, @RequestParam String avatar_url) {
        User savedUser = userService.changeAvatarUrl(username, avatar_url);
        return ResponseEntity.status(HttpStatus.CREATED).body(new ApiResponse<>(savedUser));
    }

}
